package myservice.android.activities;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.numberpicker.NumberPicker;
import myservice.android.numberpicker.NumberPicker.OnChangedListener;
import myservice.android.utilities.EditTextMonitor;
import myservice.android.utilities.ListRow;
import myservice.android.utilities.PopupMenu;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;

public class MinistryDetailsActivity extends BaseSaveableActivity {
	
	private NumberPicker ministryHoursPicker;
	private NumberPicker ministryMinutesPicker;
	private NumberPicker creditHoursPicker;
	private NumberPicker creditMinutesPicker;
	private NumberPicker magazinesPicker;
	private NumberPicker brochuresPicker;
	private NumberPicker booksPicker;
	private NumberPicker returnCallsPicker;	
	private LinearLayout creditTime, callList;
	private EditText commentsText;
	private TextView noCallsView;
	private Button saveButton, addCallButton;
	
	private int date,month,year;
	private boolean newRecord;
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		layoutId = R.layout.ministry_details;
		activityTitle = Global.res.getString(R.string.title_ministry_details);
	}

	@Override
	protected void retrieveViews() {
        ministryHoursPicker = (NumberPicker) findViewById(R.id.ministryHoursPicker);
        ministryMinutesPicker = (NumberPicker) findViewById(R.id.ministryMinutesPicker);
        creditHoursPicker = (NumberPicker) findViewById(R.id.creditHoursPicker);
        creditMinutesPicker = (NumberPicker) findViewById(R.id.creditMinutesPicker); 
        magazinesPicker = (NumberPicker) findViewById(R.id.magazinesPicker);
        brochuresPicker = (NumberPicker) findViewById(R.id.brochuresPicker);
        booksPicker = (NumberPicker) findViewById(R.id.booksPicker);
        returnCallsPicker = (NumberPicker) findViewById(R.id.returnCallsPicker); 
        creditTime = (LinearLayout) findViewById(R.id.creditTime);
        commentsText = (EditText) findViewById(R.id.commentsText);
        noCallsView = (TextView) findViewById(R.id.noCallsMessage);         
        callList = (LinearLayout) findViewById(R.id.callList);
        saveButton = (Button) findViewById(R.id.saveButton);
        addCallButton = (Button) findViewById(R.id.addCallButton);        
        
        ministryHoursPicker.setRange(0, 999);
        ministryMinutesPicker.setIncrement(5);
        ministryMinutesPicker.setRange(0, 55);        
        creditHoursPicker.setRange(0, 999);
        creditMinutesPicker.setIncrement(5);
        creditMinutesPicker.setRange(0, 55);           
        magazinesPicker.setRange(0, 999);        
        brochuresPicker.setRange(0, 999);                
        booksPicker.setRange(0, 999);                
        returnCallsPicker.setRange(0, 999);                               
	}

	@Override
	protected void loadActivityParameters() {
		date = activityParameters.getInt("date");
		month = activityParameters.getInt("month");
		year = activityParameters.getInt("year");
	}

	@Override
	protected void assignListeners() {
		
		OnChangedListener numberPickerListener = new OnChangedListener() {
			@Override
			public void onChanged(NumberPicker picker, int oldVal, int newVal) {
				activityContentModified = true;
			}			
		};		
		ministryHoursPicker.setOnChangeListener(numberPickerListener);
        ministryMinutesPicker.setOnChangeListener(numberPickerListener);        
        creditHoursPicker.setOnChangeListener(numberPickerListener);
        creditMinutesPicker.setOnChangeListener(numberPickerListener);           
        magazinesPicker.setOnChangeListener(numberPickerListener);       
        brochuresPicker.setOnChangeListener(numberPickerListener);                
        booksPicker.setOnChangeListener(numberPickerListener);              
        returnCallsPicker.setOnChangeListener(numberPickerListener);  
        
        commentsText.addTextChangedListener(new EditTextMonitor(this));
		
        saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				save();
				finish();
			}
        });
        
        addCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				final Dialog dialog = new Dialog(MinistryDetailsActivity.this);
				dialog.setContentView(R.layout.add_call_biblestudy_person_dialog);
				dialog.setTitle(Global.res.getString(R.string.title_add_new_call));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final CheckBox bibleStudyCheckbox = (CheckBox) dialog.findViewById(R.id.bibleStudyConductedCheckbox);
				final Spinner personList = (Spinner) dialog.findViewById(R.id.personSpinner);
				final EditText commentsField = (EditText) dialog.findViewById(R.id.commentsField);				
				
				Cursor c = Database.select("SELECT personid,name FROM persons WHERE timestamp<>"+Global.TIMESTAMP_DELETED+" AND status<>0 ORDER BY name");
				if (c.getCount()==0) {
					c.close();
					Global.displayToast(MinistryDetailsActivity.this, Global.res.getString(R.string.message_no_interested_defined));
					return;
				}
				String[] personNames = new String[c.getCount()];
				final long[] personIds = new long[c.getCount()];				
				int i=0;
				while (c.moveToNext()) {
					personNames[i]=c.getString(c.getColumnIndex("name"));
					personIds[i]=c.getLong(c.getColumnIndex("personid"));
					i++;						
				}				
				c.close();
				
				ArrayAdapter<String> adapter=new ArrayAdapter<String>(MinistryDetailsActivity.this,android.R.layout.simple_spinner_item,personNames);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				personList.setAdapter(adapter);								
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {	
						
						long pid = personIds[personList.getSelectedItemPosition()];
						int bibleStudy = 0;
						if (bibleStudyCheckbox.isChecked())
							bibleStudy = 1;
						
						if (Global.autoIncrementReturnCalls==true) {
							returnCallsPicker.setCurrent(returnCallsPicker.getCurrent()+1);
							activityContentModified = true;
						}
						Database.execSQL("INSERT INTO calls (callid,date,month,year,personid,territoryid,comments,biblestudy,timestamp) VALUES ("+Database.getUniqueRowId("calls")+
								         ","+date+","+month+","+year+","+pid+",0,'"+Global.fixText(commentsField.getText())+"',"+bibleStudy+","+Global.getTimeStamp()+")");	
						dialog.dismiss();
						updateList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();							
			}
        });          
        
	}
	
	private void updateList() {
		
		PopupMenu.createPopupMenu(this);
		PopupMenu.menuSection3.setVisibility(View.GONE);
		PopupMenu.menuSection4.setVisibility(View.GONE);
		
    	Cursor cursor = Database.select("SELECT * FROM calls WHERE timestamp<>"+Global.TIMESTAMP_DELETED+" AND personid<>0 AND date="+date+" AND month="+month+" AND year="+year);   		
    	
    	boolean noCallsDefined = true;
    	callList.removeAllViews();

    	while (cursor.moveToNext()) {
    		
    		noCallsDefined=false;
    		ListRow lr = new ListRow(this);
    		
    		lr.setBackgroundDrawable(Global.res.getDrawable(android.R.drawable.list_selector_background));
    		
    		lr.id=cursor.getLong(cursor.getColumnIndex("callid"));
    		
    		long personId = cursor.getInt(cursor.getColumnIndex("personid"));
			Cursor c = Database.select("SELECT name FROM persons WHERE personid="+personId);
			if (c.moveToNext()) {
				lr.firstLine.setText(c.getString(c.getColumnIndex("name")));
			}
			c.close();    		
    		
    		lr.secondLine.setText(cursor.getString(cursor.getColumnIndex("comments")));
    		int status = cursor.getInt(cursor.getColumnIndex("biblestudy"));
    		if (status == 0)
    			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.call_icon));
    		else
    			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.bible_study));
    		
    		lr.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					ListRow lr = (ListRow) view;
					save();
					clickCall(lr.id);
				}
    			
    		});
    		
            lr.setOnLongClickListener(new OnLongClickListener () {

				@Override
				public boolean onLongClick(View view) {
					ListRow lr = (ListRow) view;
    				final long cid = lr.id;
    				
    				PopupMenu.menuHeading.setText(lr.firstLine.getText());
    				
    				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_call));		
    				PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_delete_call));						
    				
    				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
    					@Override
    					public void onClick(View arg0) {
    						
    						save();
    						
    						PopupMenu.closeMenu();
    						clickCall(cid);				
    					}					
    				});
    				
    				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
    					@Override
    					public void onClick(View arg0) {
    						PopupMenu.closeMenu();
    						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MinistryDetailsActivity.this);
    						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
    						alertDialogBuilder
    							.setMessage(Global.res.getText(R.string.message_delete_call_confirmation))
    							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog,int id) {
    									if (Global.autoIncrementReturnCalls==true) {
    										if (returnCallsPicker.getCurrent()>0) {
    											returnCallsPicker.setCurrent(returnCallsPicker.getCurrent()-1);
    											activityContentModified = true;
    										}
    									}
    									Database.deleteCall(cid);
    									updateList();
    								}
    							  })
    							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog, int id) {
    									dialog.cancel();
    								}
    							});
    				 
    						AlertDialog alertDialog = alertDialogBuilder.create();
    						alertDialog.show();					
    					}					
    				});										
    				
    				PopupMenu.showMenu(view);				
    				
    				return true;
				}
            	
            });     		
    		
    		callList.addView(lr);
    		
    		View horizontalLine = new View(this);
    		horizontalLine.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,1));
    		horizontalLine.setBackgroundColor(0xFF333333);
    		callList.addView(horizontalLine);    		
    		
    	}	
    	cursor.close();
    	
    	if (noCallsDefined) {
    		callList.setVisibility(View.GONE);
    		noCallsView.setVisibility(View.VISIBLE);    		
    	} else {
    		callList.setVisibility(View.VISIBLE);
    		noCallsView.setVisibility(View.GONE);
    	}
    	
	}

	@Override
	protected void updateUi() {
		activityTitleView.setText(activityTitle+" ("+Global.getFormattedDate(year,month,date)+")");				
		
    	if (Global.trackCreditTime==true)
    		creditTime.setVisibility(View.VISIBLE);
    	else
    		creditTime.setVisibility(View.GONE);	
    	
    	Cursor cursor = Database.select("SELECT * FROM ministry WHERE date="+date+" AND month="+month+" AND year="+year);
    	
    	if (cursor.moveToNext()==true) {
    		newRecord=false;
    		ministryHoursPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("hours")));
    		ministryMinutesPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("minutes")));
    		creditHoursPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("chours")));   
    		creditMinutesPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("cminutes")));    		
    		magazinesPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("magazines")));
    		brochuresPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("brochures")));
    		booksPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("books")));
    		returnCallsPicker.setCurrent(cursor.getInt(cursor.getColumnIndex("returncalls")));
    		commentsText.setText(cursor.getString(cursor.getColumnIndex("comments")));    		
    	} else
    		newRecord=true;
    	
    	cursor.close();
    	
    	updateList();
    	
	}    
    
    @Override
    protected void save() {
    	
		activityContentModified = false;
    	
    	ministryHoursPicker.clearFocus();
    	ministryMinutesPicker.clearFocus();
    	creditHoursPicker.clearFocus();
    	creditMinutesPicker.clearFocus();
    	magazinesPicker.clearFocus();
    	brochuresPicker.clearFocus();
    	booksPicker.clearFocus();
    	returnCallsPicker.clearFocus();
    	
		if (newRecord==true) {
			Database.execSQL("INSERT INTO ministry (date,month,year,hours,minutes,chours,cminutes,magazines,brochures,books,returncalls,comments,timestamp) "+
		                            "VALUES ("+date+","+month+","+year+","+ministryHoursPicker.getCurrent()+","+ministryMinutesPicker.getCurrent()+
		                            ","+creditHoursPicker.getCurrent()+","+creditMinutesPicker.getCurrent()+","+magazinesPicker.getCurrent()+","+brochuresPicker.getCurrent()+
		                            ","+booksPicker.getCurrent()+","+returnCallsPicker.getCurrent()+",'"+Global.fixText(commentsText.getText())+"',"+Global.getTimeStamp()+")");
		} else {
			Database.execSQL("UPDATE ministry SET hours="+ministryHoursPicker.getCurrent()+", minutes="+ministryMinutesPicker.getCurrent()+", "+
									"chours="+creditHoursPicker.getCurrent()+", cminutes="+creditMinutesPicker.getCurrent()+", magazines="+magazinesPicker.getCurrent()+", "+
					                "brochures="+brochuresPicker.getCurrent()+", books="+booksPicker.getCurrent()+", returncalls="+returnCallsPicker.getCurrent()+", "+
									"comments='"+Global.fixText(commentsText.getText())+"', timestamp="+Global.getTimeStamp()+" WHERE date="+date+" AND month="+month+" AND year="+year);
		}		  
		
    }
    
	private void clickCall(long cid) {
		 Intent i = new Intent(getApplicationContext(),CallActivity.class);
	     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	     i.putExtra("call_id",cid);			     
	     startActivity(i);		
	}	    

}
